
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.abm.jwebsite.utilities;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.abm.jwebsite.exception.ProjectModeEntryIsMissingInJWebsitePropertiesException;
import org.abm.jwebsite.exception.WebsitePropertiesFileNotFoundException;
import org.abm.jwebsite.sitemap.SiteMap;

/**
 *
 * @author Saptarshi Debnath (saptarshi.devnath@gmail.com)
 */
public enum Utilities implements Constants {

    INSTANCE;
    private Properties websiteProperties;
    private String lineSeperator;
    private Logger logger = Logger.getAnonymousLogger();
    private ServletContext context;
    private String domainName;
    private Boolean debug;
    private String contextPath;
    private String pageEncoding;
    private String websiteIconPath;
    private String contentDIR;

    /**
     *
     */
    public void init(HttpServletRequest request) {
        if (this.websiteProperties == null) {
            this.websiteProperties = new Properties();
            this.context = request.getSession().getServletContext();
            try {
                String propertiesFilePath = this.getRealPath(CNST_JWEBSITE_PROPERTIES_RELATIVEPATH);
                this.websiteProperties.load(new FileReader(new File(propertiesFilePath)));
            } catch (IOException ex) {
                throw new WebsitePropertiesFileNotFoundException(ex);
            }
            this.lineSeperator = System.getProperty("line.separator");
            this.domainName = request.getServerName();
            this.contextPath = request.getContextPath();
            this.pageEncoding = this.getProperty("jwebsite.page.encoding");
            this.websiteIconPath = this.getProperty("jwebsite.site.icon");
            this.contentDIR = this.getProperty(CNST_KEY_CONTENT_DIRECTORY);
            this.logInfo("Utilities initialized successfully");
        } else {
            this.log(Level.WARNING, "Utilities already initialized.");
        }
    }

    public String getRealPath(String realtivePath) {
        return this.context.getRealPath(realtivePath);
    }

    public String getProperty(String key) {
        return this.websiteProperties.getProperty(key).trim();
    }

    /*
     * public void setProperty(String key, String value){
     * this.websiteProperties.setProperty(key, value);
     * }
     */
    public String getLineSeperator() {
        return lineSeperator;
    }

    public void log(Level level, String message) {
        if (this.isDebug()) {
            this.logger.log(level, "{0}{1}---------------------------", new Object[]{message, this.getLineSeperator()});
        }
    }

    public void logInfo(String message) {
        this.log(Level.INFO, message);
    }

    public static void setPageID(HttpServletRequest request, String pageID) {
        request.setAttribute(CNST_PAGE_ID, pageID);
    }

    public boolean isProductionEnvironment() {
        boolean isProduction = false;
        if (this.getProperty(CNST_KEY_PRODUCTION_URL).equalsIgnoreCase(domainName)) {
            isProduction = true;
        }
        return isProduction;
    }

    public boolean isDebug() {
        if (this.debug == null) {
            if (this.isProductionEnvironment()) {
                this.debug = Boolean.parseBoolean(this.getProperty(CNST_KEY_DEBUG_PROD));
            } else {
                this.debug = Boolean.parseBoolean(this.getProperty(CNST_KEY_DEBUG_TEST));
            }
        }

        return this.debug;
    }

    public String getContextPath() {
        return contextPath;
    }

    public static SiteMap getSiteMap(HttpServletRequest request) {
        return (SiteMap) request.getAttribute(CNST_REQUEST_NAME_SITEMAP);
    }

    public String getPageEnconding() {
        return this.pageEncoding;
    }

    public String getWebsiteIcon() {
        return this.websiteIconPath;
    }

    public String getProjectMode() {
        String mode = this.getProperty(Constants.CNST_KEY_PROJECT_MODE);
        if (mode == null || !(mode.equalsIgnoreCase(CNST_PROJECT_MODE_PRODUCTION) || mode.equalsIgnoreCase(CNST_PROJECT_MODE_DEVELOPMENT))) {
            throw new ProjectModeEntryIsMissingInJWebsitePropertiesException("Currently supplied value is " + mode);
        }
        return mode;
    }

    public String importStaticResource(String resourceURI) {
        String output;
        String resourcePath = this.contextPath + resourceURI;
        resourceURI = resourceURI.toLowerCase();
        if (resourceURI.endsWith(CNST_EXTENTION_JS)) {
            output = "<script type=\"text/javascript\" src=\"" + resourcePath + "\"></script>";
        } else if (resourceURI.endsWith(CNST_EXTENTION_CSS)) {
            output = "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + resourcePath + "\" />";
        } else {
            output = "";
        }
        return output;
    }

    public String setGetParameter(String url, String paramName, String paramValue) throws UnsupportedEncodingException {
        String appendValue = URLEncoder.encode(paramValue, this.getPageEnconding());
        if (url.contains("?")) {
            url = url + "&" + paramName + "=" + appendValue;
        } else {
            url = url + "?" + paramName + "=" + appendValue;
        }
        return url;
    }

    public static String getReconstructedURL(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        String queryString = request.getQueryString();
        String url = null;
        if (queryString == null) {
            url = requestURL.toString();
        } else {
            url = requestURL.append('?').append(queryString).toString();
        }
        return url;
    }

    public String getResourcePathByPageID(String pageID) {
        return this.contentDIR + pageID + ".jsp";
    }

    public String getResourcePathByPageID(HttpServletRequest request) {
        return this.getResourcePathByPageID(this.getPageID(request));
    }

    public String getPageID(HttpServletRequest request) {
        return (String) request.getAttribute(CNST_PAGE_ID);
    }
    
    /**
     * Returns the current domain name On which this application is running.  
     * @return
     */
    public String getCurrentDomainName(HttpServletRequest request){
    	return request.getServerName();
    }

}
